package com.SuperUtility;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

/**
 * 
 * @author Goofy
 * @Date 2015年7月6日 上午11:22:32
 */
public class Usage {
	
	static Thread thread = null;
	
	public static String readTxtFile(String filePath) {
		StringBuilder content = new StringBuilder("");
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) {
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					content.append(lineTxt);// txt换行
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return content.toString();
	}

	public static void main(String[] args) throws Exception {
		String params = readTxtFile("d://params.txt");
		final File file = new File(params);
		thread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					new WatchDir(file, true, new FileActionCallback() {
						@Override
						public void create(File file) {
							System.out.println("文件已创建\t" + file.getAbsolutePath());
							if(file.getAbsolutePath().endsWith("M3.txt")) {
								try {
									Runtime.getRuntime().exec("cmd /c print /d:\\\\localhost\\G500 " + file.getAbsolutePath().toString()+" && del "+file.getAbsolutePath().toString()+" exit");
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} 
							}
							if(file.getAbsolutePath().endsWith("M3.zip")) {
								try {
									AntZipUtils.unZip(file.getAbsolutePath().toString(), file.getParentFile().getAbsolutePath());
									file.delete();
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						}

						@Override
						public void delete(File file) {
							System.out.println("文件已删除\t" + file.getAbsolutePath());
						}

						@Override
						public void modify(File file) {
							System.out.println("文件已修改\t" + file.getAbsolutePath());
//							if(file.getAbsolutePath().endsWith("M3.txt")) {
//								try {
//									Runtime.getRuntime().exec("cmd /c cmd.exe /c print /d:\\\\localhost\\G500 " + file.getAbsolutePath().toString()+" exit");
//								} catch (Exception e) {
//									// TODO Auto-generated catch block
//									e.printStackTrace();
//								} 
//							}
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
		thread.start();

		System.out.println("正在监视文件夹:" + file.getAbsolutePath() + "的变化");
	}
	
	public static void stopFileWatch() {
		thread.interrupt();
	}

}
